//
//  LanguageTool.m
//  语言切换
//
//  Created by dllo on 15/12/3.
//  Copyright © 2015年 牟江辉. All rights reserved.
//

#import "LanguageTool.h"

@implementation LanguageTool
static NSBundle *bundle = nil;

+ (instancetype)shareLanguage{
    static LanguageTool *single;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        single = [[LanguageTool alloc]init];
    });
    return single;
}

#pragma mark - Method AllLanguages
+ (NSArray *)AllLanguages {
    NSUserDefaults *defaults = [ NSUserDefaults standardUserDefaults ];
    // 取得 iPhone 支持的所有语言设置
    NSArray *languages = [defaults objectForKey : @"AppleLanguages"];
    return languages;
}

+ ( NSBundle * )bundle{
    return bundle;
}
#pragma mark 初始化语言
+(void)initUserLanguage{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *string = [def valueForKey:@"userLanguage"];
    if(string.length == 0){
        //获取系统当前语言版本
        NSArray* languages = [def objectForKey:@"AppleLanguages"];
        NSString *current = [languages objectAtIndex:0];
        string = current;
        [def setValue:current forKey:@"userLanguage"];
        [def synchronize];//持久化，不加的话不会保存
    }
    //获取文件路径
    NSString *path = [[NSBundle mainBundle] pathForResource:string ofType:@"lproj"];
    bundle = [NSBundle bundleWithPath:path];//生成bundle
}
#pragma mark 获取语言
+(NSString *)userLanguage{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *language = [def valueForKey:@"userLanguage"];
    return language;
}
#pragma mark 设置语言
+(void)setUserlanguage:(NSString *)language{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    //1.第一步改变bundle的值
    NSString *path = [[NSBundle mainBundle] pathForResource:language ofType:@"lproj"];
    bundle = [NSBundle bundleWithPath:path];
    //2.持久化
    [def setValue:language forKey:@"userLanguage"];
    [def synchronize];
}
@end
